/*
 * @Author: your name
 * @Date: 2020-10-04 18:06:06
 * @LastEditTime: 2021-07-17 22:22:05
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \background\controller\middle\auth.go
 */
package middle

import (
	"background/config"
	"background/controller"
	"background/model"
	"encoding/json"
	"log"

	"github.com/gin-gonic/gin"
)

func AuthMiddle(c *gin.Context) {
	token := c.Query("token")
	user := c.Query("userid")
	if user == "" || token == "" {
		log.Print("error user not existed or token missing")
		log.Print(c.Request.URL.String())
		c.JSON(200, controller.RespBase{
			"auth err", 20, nil,
		})
		c.Abort()
		return
	}
	cli :=  config.RedisOne()
	
	if cli != nil{
			
		if cli.Exists(token).Val() {
			users := model.Users{}
			userInfo := config.RedisOne().Get(token).Val()
			e := json.Unmarshal([]byte(userInfo), &users)
			if nil != e {
				c.JSON(200, controller.RespBase{
					"auth err", 10, nil,
				})
				c.Abort()
				return
			}
		} else {
			c.JSON(200, controller.RespBase{
				"expired or no login", 210, nil,
			})
			c.Abort()
			return
		}
		c.Next()
	}
}
